package cn.wolfcode.crud.web.controller;

import cn.wolfcode.crud.domain.Department;
import cn.wolfcode.crud.domain.Employee;
import cn.wolfcode.crud.domain.Role;
import cn.wolfcode.crud.qo.EmployeeQueryObject;
import cn.wolfcode.crud.qo.PageResult;
import cn.wolfcode.crud.qo.QueryObject;
import cn.wolfcode.crud.service.IDepartmentService;
import cn.wolfcode.crud.service.IEmployeeService;
import cn.wolfcode.crud.service.IRoleService;
import cn.wolfcode.crud.util.JsonResult;
import cn.wolfcode.crud.util.RequiredPermission;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo")EmployeeQueryObject qo) {

       // Subject subject = SecurityUtils.getSubject();
        //System.out.println("判断是否有hr的角色" +subject.hasRole("HR_MGR"));
        //System.out.println(subject.isPermitted("employee:list"));
        //System.out.println(subject.isPermitted("role:list"));
        // System.out.println(subject.isPermitted("department:list"));

        //查询所有部门数据,方便页面回显
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments",departments);
        model.addAttribute("pageInfo",employeeService.query(qo));
        return  "employee/list";
    }

    @RequiredPermission("员工删除")
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id != null) {
            employeeService.delete(id);
        }
        return "redirect:/employee/list.do";
    }

    @RequiredPermission( "员工编辑页面")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        List<Role> roles= roleService.listAll();
        model.addAttribute("roles",roles);

        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments",departments);
        if (id != null) {
          Employee employee =  employeeService.get(id);
          model.addAttribute("employee",employee);
        }

        return "/employee/input";
    }
    @RequiredPermission("员工新增/修改")
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee,Long[] ids){

        try {

            if (employee.getId() != null) {
                employeeService.update(employee,ids);
            }else {
                employeeService.save(employee,ids);
            }
            return new JsonResult();
        }catch (Exception e){
            return new JsonResult(false,"操作失败");
        }

    }

    @RequestMapping("/batchDelete")
    @RequiredPermission("员工批量删除")
    @ResponseBody
    public JsonResult batchDelete(Long[] ids){

        try {

            if (ids!=null && ids.length>0) {

                employeeService.batchDelete(ids);
            }
            return new JsonResult();
        }catch (Exception e){
            return new JsonResult(false,"操作失败");
        }
    }

    @RequestMapping("/checkName")
    @ResponseBody
    public Map<String,Boolean> checkName(String name,Long id){  // valid:true
        HashMap<String, Boolean> map = new HashMap<>();
        //如果id有值,表示为编辑
        if (id!=null) {
            //先去数据库查这个人
            Employee employee = employeeService.get(id);
            //如果当前的name跟数据库的名字相同,就返回true
            if (name.equals(employee.getName())) {
                map.put("valid",true);
                return map;
            }
        }
        //新增的时候根据用户名去查是否已经存在
        Employee employee = employeeService.selectByName(name);
        map.put("valid",employee==null);
        return map;
    }

    //导出的方法
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {

        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");

        //创建excel文件
        Workbook wb =  employeeService.exportXls();

        //把文件输出到浏览器
        wb.write(response.getOutputStream());
    }


    //添加导入的方法
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws IOException {
       employeeService.importXls(file);
        return new JsonResult();
    }

}
